#!/usr/bin/perl
#copyright Ian Baker 2007

use Time::HiRes qw(usleep);
use IO::Select;
use POSIX;

sysopen(SER, "/dev/ttyS0", O_RDWR|O_NONBLOCK|O_NOCTTY|O_EXCL) ||
  die "Couldn't open /dev/ttyS0: $!";
#open(IFO, "+>&IFI")
#    or die "can't dup ifi0: $!";
my $ofh = select(SER); $| = 1; select($ofh);
my $sel = new IO::Select(SER);

my $t = POSIX::Termios->new;
$t->getattr(fileno(SER));
$t->setispeed('B9600');
$t->setospeed('B9600');
$t->setattr(fileno(SER), TCSANOW);

$| = 1;

while(1) {
  foreach(7) {
    syswrite(SER,chr(0),1);
    if($_ <= 48) {
      my $out;
      my $out = recv_serial(SER);
      print "$_:" . ord($out) . "\n";
    } else {
      print "firing $_\n";
    }    
    usleep(100000);
  }
#  print "loop\n";
}


sub recv_serial {
    # low-level serial read

    my $fh = shift;

    # nope - no waiting!
    # wait for data. timeout is 20ms.
    # is this the right way to use 4-arg select in this context?
    #my $rin;
    #vec($rin, fileno(IFI), 1) = 1;
    #my $nfound = select($rin, undef, undef, 0);
    
    # read a byte.
#    if($sel->can_read(0)) {
#      print "reading\n";
      sysread(SER, $result, 1);
#    }

    return $result || undef;
}
